<?php

// import a service
include_service('FileUploadProcessor');

/**
 * User picture upload processor
 * @author ReGeDa
 */
class UserPictureUpload implements FileUploadProcessor {

	/**
	 * @see ./system/plugins/service/FileUploadProcessor.php
	 */
	public function file($path, $origname, $size, $mime) {

		$image = &platcode()->plugins->import('Image');
		/* @var $image Image */

		// validate & post error
		$info = $image->validate($path, array('min_size' => 150));

		// if success validation
		if ($info !== FALSE) {
			
			// set size for image
			$info['size'] = 150;

			// read content after resizing
			$image->resize($path, $info);

			////////////////////// DATABASE STORAGE

			// input data
			$now = time(); // load date
			$handle = fopen($path, "rb"); // picture source

			$stmt = database()->prepare('SELECT set_user_pic(?,?,?,?)');
			/* @var $stmt PDOStatement */

			$stmt->bindValue(1, SESSION_ID);
			$stmt->bindValue(2, $info['type'], PDO::PARAM_INT);
			$stmt->bindValue(3, $now, PDO::PARAM_INT);
			$stmt->bindValue(4, $handle, PDO::PARAM_LOB);

			// result path
			$stmt->bindColumn(1, $path);

			try {

				$stmt->execute();
				$stmt->fetch();

				// post image URL
				platcode()->raw['url'] = '/media/userpic/'.$path.image_type_to_extension($info['type']);

			} catch (PDOException $e) {
				platcode()->raw['err'] = 'Failed to save in database';
			}

			// free source
			fclose($handle);
		}
		// exit
		return TRUE;
	}
}

//-------------------------------------------------- HANDLER

/**
 * Account Handler
 * @author ReGeDa
 * @events :create :login :activate :edit
 */
class Account_Handler extends Event_Handler {

	/**
	 * Constructor
	 */
	public function  __construct() {
		parent::__construct();
		// load language
		platcode()->lang->load('account');
	}

	/**
	 * View account page
	 * @param string $title_name
	 * @param string $xslt_name
	 */
	private function view_page($title_name, $xslt_name) {
		// set variables
		platcode()->raw['page-title'] = lang($title_name);

		// import javascript
		platcode()->plugins->import('JavaScript')
			->lang(array('global-lang','form-lang','account-lang'))
			->lib(array('jdog-form','p-common','p-account'));

		// output
		$this->output->prepare_xslt('account/'.$xslt_name);
	}

	/**
	 * Registration page
	 * @param string $outtype
	 */
	public function on_create($outtype = NULL) {

		// select response type
		switch ($outtype) {
			case 'xml':
			case 'json':

				// set rules
				$rules = array(
					'email' => 'required : email : strtolower',
					'secret' => 'required : pass_strength',
					'username' => 'required : min_len[3] : max_len[15] : pattern[[a-z][a-z\d]+]',
					'captcha' => 'required : captcha'
				);

				// validate input
				if (platcode()->plugins->import('Validation')->validate($rules, STANDART_VALIDATOR)) {
					// create a new passport
					$this->send_message('model/user/passport', 'new');
				}

				// set output type
				$this->output->type = $outtype;

				break;
			
			// view XHTML
			default:

				// check user session
				if (is_user_session())
					platcode()->plugins->import('HTTP')->redirect(SESSION_NAME);
				else
					// output
					$this->view_page('account_creation', 'create');
		}
	}

	/**
	 * Login page
	 * @param string $outtype
	 */
	public function on_login($outtype = NULL) {

		// select response type
		switch ($outtype) {
			case 'xml':
			case 'json':

				// set output type
				$this->output->type = $outtype;

				// input rules
				$rules = array(
					'secret' => 'required'
				);

				// by EMAIL
				if (isset($_POST['email'])) {
					$rules['email'] = 'required : email : strtolower';
					$column = 'email';
				}
				// by USERNAME
				else if (isset($_POST['username'])) {
					$rules['username'] = 'required : pattern[[a-z][a-z\d]+]';
					$column = 'username';
				}
				// no set...
				else {
					platcode()->raw['err'] = lang('email_or_username');
					// exit from handler
					return;
				}

				// validate input
				if (platcode()->plugins->import('Validation')->validate($rules, STANDART_VALIDATOR)) {
					// validate a passport
					$this->send_message('model/user/passport', 'validate', $column);
				}

				break;

			// view XHTML
			default:

				// check user session
				if (is_user_session())
					platcode()->plugins->import('HTTP')->redirect(SESSION_NAME);
				else
					// output
					$this->view_page('account_enter', 'enter');
		}
	}

	/**
	 * Close a user session
	 */
	public function on_logout() {

		$session = &platcode()->plugins->import('Session');

		if ($session->validate_client('generate_user_session'))
			$session->free_client(SESSION_ID);

		// go to ROOT
		platcode()->plugins->import('HTTP')->redirect();
	}

	/**
	 * Activate a user account
	 * @param string $id
	 * @param string $hash
	 */
	public function on_activate($id, $hash = NULL) {

		$AQ = &platcode()->plugins->import('ActiveQuery');
		/* @var $AQ ActiveQuery */

		$AQ->set(array(
			'id' => $id,
			'salt' => config('password_salt')
		));

		// activate by ID
		if (is_null($hash)) {
			$AQ->set('ttl', config('lazy_user_timeout'));
			$activator = 'activate_id';
		}
		// activate from E-mail
		else {
			$AQ->set(array(
				'hash' => $hash,
				'ttl' => config('untrust_email_life')
			));
			$activator = 'activate_email';
		}

		// prepare SQL
		$stmt = database()->prepare($AQ->call($activator));
		/* @var $stmt PDOStatement */

		try {
			// query
			$AQ->query($stmt);

			// session data
			// [name, hash]
			$data = $stmt->fetch(PDO::FETCH_ASSOC);

			// save session
			platcode()->plugins->import('Session')->allocate_client($id, $data, 0);

			// redirect to home page
			// (username).html
			platcode()->plugins->import('HTTP')->redirect($data['name']);
		
		} catch (PDOException $e) {

			throw new Platcode_Exception('Access Denied', 403);
		}
	}

	/**
	 * Settings page
	 * @param string $outtype
	 */
	public function on_edit($outtype = NULL) {

		switch ($outtype) {
			case 'xml':
			case 'json':

				$this->output->type = $outtype;

				break;

			// user picture uploading
			case 'script':

				// check a user session
				if (is_user_session()) {

					$upload = &platcode()->plugins->import('FileUpload');
					/* @var $upload FileUpload */

					$upload->set_allowed_ftypes('gif|png|jpeg');

					// process uploading
					if ( ! $upload->run('userpic', new UserPictureUpload()))
						// output error
						platcode()->raw['err'] = $upload->get_last_error();

					// callback javascript
					$this->output->type = 'jcallback';
				}
				// access is denied
				else {
					throw new Platcode_Exception(
						lang('access_denied'),
						403
					);
				}

				break;

			default:
				// check a user session
				if (is_user_session()) {

					$this->send_message('model/help/utils', 'directory', 'countries');
					$this->send_message('model/help/utils', 'directory', 'languages');
					$this->send_message('model/user/profile', 'volatile_data');
					
					// output
					$this->view_page('account_update', 'edit');
				}
				// go to start on error
				else
					platcode()->plugins->import('HTTP')->redirect();
		}
	}

}

// end of file